package com.hulk.dryad.manage.config;

import com.hulk.dryad.manage.s3.S3FsProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.sts.StsAsyncClient;
import software.amazon.awssdk.services.sts.StsClient;

import java.net.URI;

/**
 * 文件系统服务自动配置
 *
 * @author hulk
 */
@Configuration
@ConditionalOnProperty(name = "s3.enable", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(S3FsProperties.class)
public class S3FsClientConfig {

	@Bean
	public StsClient stsClient(S3FsProperties properties) {
		return StsClient.builder()
				.endpointOverride(getEndpointUri(properties))
				.credentialsProvider(getCredentialsProvider(properties))
				.region(Region.of(properties.getRegion()))
				.build();
	}

	@Bean
	public StsAsyncClient stsAsyncClient(S3FsProperties properties) {
		return StsAsyncClient.builder()
				.endpointOverride(getEndpointUri(properties))
				.credentialsProvider(getCredentialsProvider(properties))
				.region(Region.of(properties.getRegion()))
				.build();
	}

	@Bean
	public S3Client s3Client(S3FsProperties properties) {
		return S3Client.builder()
				.endpointOverride(getEndpointUri(properties))
				.credentialsProvider(getCredentialsProvider(properties))
				.region(Region.of(properties.getRegion()))
				.build();
	}

	@Bean
	public S3AsyncClient s3AsyncClient(S3FsProperties properties) {
		return S3AsyncClient.builder()
				.endpointOverride(getEndpointUri(properties))
				.credentialsProvider(getCredentialsProvider(properties))
				.region(Region.of(properties.getRegion()))
				.build();
	}

	private static URI getEndpointUri(S3FsProperties properties) {
		// 拼接 url
		String scheme = properties.isUseHttps() ? "https" : "http";
		String endpoint = properties.getEndpoint();
		String endpointUrl = String.format("%s://%s", scheme, endpoint);
		return URI.create(endpointUrl);
	}

	private static StaticCredentialsProvider getCredentialsProvider(S3FsProperties properties) {
		return StaticCredentialsProvider.create(AwsBasicCredentials.create(properties.getAccessKey(), properties.getSecretKey()));
	}

}
